package com.ship.dispatch.service.fob.impl;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.ship.common.core.exception.BusException;
import com.ship.common.core.web.domain.BaseResultCode;
import com.ship.dispatch.bean.SpArrangeSchemeDetail;
import com.ship.dispatch.bean.SpDispatchSchemeDetail;
import com.ship.dispatch.bean.SpDispatchSchemeExecute;
import com.ship.dispatch.bean.SpPortInformation;
import com.ship.dispatch.bean.fob.*;
import com.ship.dispatch.bean.orderPay.ConInsuranceGoods;
import com.ship.dispatch.bean.orderPay.SpPaymentOrder;
import com.ship.dispatch.bo.orderPay.SpPaymentOrderBO;
import com.ship.dispatch.bo.orderPay.SpPaymentOrderDetailBO;
import com.ship.dispatch.bpm.utils.CalculateDateUtil;
import com.ship.dispatch.bpm.utils.JsonUtils;
import com.ship.dispatch.bpm.utils.TemplateParamUtils;
import com.ship.dispatch.bpm.vo.ManageEntityVo;
import com.ship.dispatch.mapper.SpArrangeSchemeDetailMapper;
import com.ship.dispatch.mapper.SpPortInformationMapper;
import com.ship.dispatch.mapper.fob.SpFobGmbxMapper;
import com.ship.dispatch.mapper.fob.SpFobZzgcjrMapper;
import com.ship.dispatch.mapper.orderPay.ConInsuranceGoodsMapper;
import com.ship.dispatch.service.SpDispatchSchemeDetailService;
import com.ship.dispatch.service.SpDispatchSchemeExecuteService;
import com.ship.dispatch.service.fob.SpFobFileRecordService;
import com.ship.dispatch.service.fob.SpFobGmbxService;
import com.ship.dispatch.service.fob.SpFobSyzlxzwjService;
import com.ship.dispatch.service.fob.SpFobTemplateService;
import com.ship.dispatch.service.orderPay.SpPaymentOrderService;
import com.ship.dispatch.util.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

/**
 *@title SpFobGmbxServiiceImpl
 *@description 购买保险
 *@author yl
 *@create 2023/12/16 0016
 */
@Service
public class SpFobGmbxServiiceImpl extends FobBaseServiceImpl<SpFobGmbxMapper, SpFobGmbx> implements SpFobGmbxService {

    @Autowired(required = false)
    SpFobGmbxMapper spFobGmbxMapper;

    @Autowired
    SpFobFileRecordService spFobFileRecordService;

    @Autowired
    SpDispatchSchemeExecuteService schemeDetailService;

    @Autowired
    SpFobTemplateService spFobTemplateService;

    @Autowired(required = false)
    SpPortInformationMapper spPortInformationMapper;

    @Override
    public void updateEntity(ManageEntityVo manageEntityVo, String json) {
        SpFobGmbx object = JsonUtils.jsonToObject(json,SpFobGmbx.class);
        SpFobGmbx his = spFobGmbxMapper.selectOne(new LambdaQueryWrapper<SpFobGmbx>().eq(SpFobGmbx::getProceeInstanceId,manageEntityVo.getProcessInstanceId()).ne(SpFobGmbx::getStatus,-2));
        if(manageEntityVo.getOperationType()==1) {
            object.setStatus(1);
        }
        if(his==null){ // 新增
            object.setSchemeDetailId(manageEntityVo.getSchemeDetailId());
            object.setTaskId(manageEntityVo.getTaskId());
            object.setProceeInstanceId(manageEntityVo.getProcessInstanceId());
            spFobGmbxMapper.insert(object);
        }else { // 修改
            object.setId(his.getId());
            BeanUtils.copyProperties(object,his);
            spFobGmbxMapper.updateById(his);
            // 处理多余文件记录
            List<String> ids = new ArrayList<>();
            his = spFobGmbxMapper.selectOne(new LambdaQueryWrapper<SpFobGmbx>().eq(SpFobGmbx::getProceeInstanceId,manageEntityVo.getProcessInstanceId()).ne(SpFobGmbx::getStatus,-2));
            if((his.getFiels()!=null && his.getFiels().length()>0)){
                String temp = his.getFiels();
                String[] fieldIds = temp.split(",");
                ids =  Arrays.stream(fieldIds).collect(Collectors.toList());
            }
            if(StringUtils.isNotEmpty(his.getSlip())){
                String temp = his.getSlip();
                String[] fieldIds = temp.split(",");
                List<String> templIds =  Arrays.stream(fieldIds).collect(Collectors.toList());
                ids.addAll(templIds);
            }
            spFobFileRecordService.deleteOtherFileRecor(his.getId(),ids);
        }
    }

    @Override
    public SpFobBaseBean getBaseBeanByInstanceId(String id) {
        return spFobGmbxMapper.selectOne(new LambdaQueryWrapper<SpFobGmbx>().eq(SpFobGmbx::getProceeInstanceId,id).ne(SpFobGmbx::getStatus,-2));
    }
    @Override
    public void  saveEntity(SpFobBaseBean bean){
        SpFobGmbx spFobZzgcjr = new SpFobGmbx();
        BeanUtils.copyProperties(bean,spFobZzgcjr);
        this.save(spFobZzgcjr);
    }

    @Override
    public void updateEntityById(SpFobBaseBean bean) {
        SpFobGmbx spFobZzgcjr = new SpFobGmbx();
        BeanUtils.copyProperties(bean,spFobZzgcjr);
        this.updateById(spFobZzgcjr);
    }


    @Override
    public Object getFormData(String id,Long serviceId) {
        SpFobGmbx spFobZzgcjr = null;
        if(serviceId!=null){
            spFobZzgcjr = spFobGmbxMapper.selectById(serviceId);
        }else {
            spFobZzgcjr = spFobGmbxMapper.selectOne(new LambdaQueryWrapper<SpFobGmbx>().eq(SpFobGmbx::getProceeInstanceId,id).ne(SpFobGmbx::getStatus,-2));
        }
        if(spFobZzgcjr==null){
            return null;
        }
        if(StringUtils.isEmpty(spFobZzgcjr.getCostUnit())){
            spFobZzgcjr.setCostUnit("2");
        }
        //默认保险合同信息
        if(StringUtils.isEmpty(spFobZzgcjr.getConId())){
            Map<String,Object> tempMap = spFobGmbxMapper.selectConInsuranceGoods(null);
            if(tempMap!=null){
                spFobZzgcjr.setConId(tempMap.get("id")+"");
            }
        }
        Map<String,Object> map = JsonUtils.jsonToMap(JsonUtils.objectToJson(spFobZzgcjr), Object.class);
        if(StringUtils.isNotBlank(spFobZzgcjr.getFiels())){
            String[] ids = spFobZzgcjr.getFiels().split(",");
            List<Long> resId = new ArrayList<>();
            for(String tempId:ids){
                if (StringUtils.isNotBlank(tempId)) {
                    resId.add(Long.parseLong(tempId));
                }
            }
            List<SpFobFileRecord> spFobFileRecordList =  spFobFileRecordService.listByIds(resId);
            map.put("fiels",spFobFileRecordList);
        }
        SpDispatchSchemeExecute execute = schemeDetailService.getExceuteByInstanceId(spFobZzgcjr.getProceeInstanceId());
        if (execute.getExpectedLoadingPort()!=null && spFobZzgcjr.getPort() == null){
            map.put("port",execute.getExpectedLoadingPort());
        }
        if(spFobZzgcjr.getSlip()!=null){
            String[] ids = spFobZzgcjr.getSlip().split(",");
            List<Long> resId = new ArrayList<>();
            for(String tempId:ids){
                if (StringUtils.isNotBlank(tempId)) {
                    resId.add(Long.parseLong(tempId));
                }
            }
            List<SpFobFileRecord> spFobFileRecordList =  spFobFileRecordService.listByIds(resId);
            map.put("slip",spFobFileRecordList);
        }

        return map;
    }

    @Override
    public String  getTemplateParam(ManageEntityVo manageEntityVo) {
        ObjectNode json = manageEntityVo.getData();
        SpFobGmbx spFobZzgcjr = JsonUtils.jsonToObject(JsonUtils.objectToJson(json),SpFobGmbx.class);
        String  templateId = spFobZzgcjr.getTemplateId();
        if(templateId==null){
            throw  new BusException("请选模板后再生成模板正文", BaseResultCode.GENERAL_ERROR);
        }
        SpFobTemplate spFobTemplate = spFobTemplateService.getById(templateId);
        if(spFobTemplate == null){
            throw  new BusException("当前模板不存在，请联系管理员处理", BaseResultCode.GENERAL_ERROR);
        }
        // 调度方案信息
        SpDispatchSchemeExecute schemeDetail = schemeDetailService.getExceuteByInstanceId(manageEntityVo.getProcessInstanceId());
        Map<String,String> map = new HashMap<>();
        if(schemeDetail!=null){
            Map<String,String> tempMap = JsonUtils.jsonToMap(JsonUtils.objectToJson(schemeDetail),String.class);
            for(String key:tempMap.keySet()){
                map.put("spDispatchSchemeDetail."+key,tempMap.get(key));
            }
        }
        if(schemeDetail.getExpectedLoadingPort()!=null){ // 获取港口信息
            SpPortInformation spPortInformation = spPortInformationMapper.selectOne(new LambdaQueryWrapper<SpPortInformation>()
                    .eq(SpPortInformation::getPortNameEnglish,schemeDetail.getExpectedLoadingPort())
                    .or().eq(SpPortInformation::getPortNameChinese,schemeDetail.getExpectedLoadingPort())
                    .last("LIMIT 1")
            );
            if(spPortInformation!=null){
                map.put("spPortInformation.portCountry",spPortInformation.getPortCountry());
            }else{
                map.put("spPortInformation.portCountry","");
            }
        }
        if(schemeDetail.getTradeBody()==1){
          //  map.put("temp1","Hong kong");
            map.put("temp1","Gas and Power Trading& Marketing Limited");
        }else {
            //map.put("temp1","Singapore");
            map.put("temp1","Gas and Power Singapore Trading& Marketing Pte. Ltd");
        }
        // 当前业务表单信息
        if(json!=null){
            Map<String,String> tempMap = JsonUtils.jsonToMap(JsonUtils.objectToJson(json),String.class);
            for(String key:tempMap.keySet()){
                map.put("spFobGmbx."+key,tempMap.get(key));
            }
        }
        String template = "";
        if(spFobTemplate !=null){
            template = TemplateParamUtils.processDynamicParams(spFobTemplate.getContent(),map);
        }
        return template;
    }


    @Override
    public SpFobGmbx findData(String processInstanceId) {
        SpFobGmbx spFobZzgcjr = spFobGmbxMapper.selectOne(new LambdaQueryWrapper<SpFobGmbx>().eq(SpFobGmbx::getProceeInstanceId,processInstanceId).ne(SpFobGmbx::getStatus,-2));
        return spFobZzgcjr;
    }

    @Override
    public List<Long> findServieData(String processInstanceId){
        List<SpFobGmbx> spFobBaseBeans =  spFobGmbxMapper.selectList(new LambdaQueryWrapper<SpFobGmbx>().eq(SpFobGmbx::getProceeInstanceId,processInstanceId).orderByDesc(SpFobGmbx::getCreateDate));
        List<Long> list = spFobBaseBeans.stream().map(SpFobBaseBean::getId).collect(Collectors.toList());
        return list;
    }


    public void createPayOrder(Long id){
        SpFobGmbx his = this.getById(id);
        if(his!=null && his.getOrderId()==null){
            Long orderId = createPayOrder(his.getProceeInstanceId(),his);
            his.setOrderId(orderId);
            this.updateById(his);
        }
    }

    @Autowired
    SpFobSyzlxzwjService spFobSyzlxzwjService;

    @Autowired
    SpPaymentOrderService spPaymentOrderService;

    @Autowired(required = false)
    SpArrangeSchemeDetailMapper spArrangeSchemeDetailMapper;

    @Autowired(required = false)
    ConInsuranceGoodsMapper conInsuranceGoodsMapper;
    /**
     * 创建支付订单
     * @param processInstanceId
     * @param his
     */
    public Long createPayOrder(String processInstanceId,SpFobGmbx his){
        SpDispatchSchemeExecute execute = schemeDetailService.getExceuteByInstanceId(processInstanceId);
        SpPaymentOrderBO spPaymentOrderBO = new SpPaymentOrderBO();
        //保险费用
        spPaymentOrderBO.setContractType(2);
        spPaymentOrderBO.setOrderType(6);
        if(his.getFobCost()!=null){
            spPaymentOrderBO.setPayAmount(BigDecimal.valueOf(Long.parseLong(his.getFobCost())));
        }
        spPaymentOrderBO.setVoyageNo(execute.getVoyageNo());
        spPaymentOrderBO.setOrderStatus(2);
        spPaymentOrderBO.setPayAmountUnit(2);
        if(StringUtils.isNotEmpty(his.getConId())){
            //获取保险合同 关联
            ConInsuranceGoods insuranceGoods  = conInsuranceGoodsMapper.selectById(his.getConId());
            if (insuranceGoods!=null){
                spPaymentOrderBO.setContractId(insuranceGoods.getId());
                spPaymentOrderBO.setContractName(insuranceGoods.getContractName());
            }
        }
        //spPaymentOrderBO.setc
        SpPaymentOrder order = spPaymentOrderService.synchronousPayOrder(spPaymentOrderBO);

        //对于订单明细
        SpPaymentOrderDetailBO spPaymentOrderDetailBO = new SpPaymentOrderDetailBO();
        spPaymentOrderDetailBO.setOrderId(order.getId());
        spPaymentOrderDetailBO.setPayableAmount(BigDecimal.valueOf(Long.parseLong(his.getFobCost())));
        //spPaymentOrderDetailBO.set
        if("1".equals(execute.getTradeBody())){
            spPaymentOrderDetailBO.setCnoocCorporation("CNOOC Gas and Power Trading& Marketing Limited");
        }else {
            spPaymentOrderDetailBO.setCnoocCorporation("CNOOC Gas and Power Singapore Trading& Marketing Pte. Ltd");
        }
        //预保单
        spPaymentOrderDetailBO.setAdvancePolicyInfo("1");
        spPaymentOrderDetailBO.setShipName(execute.getShipName());
        spPaymentOrderDetailBO.setExpectedLoadingPort(execute.getExpectedLoadingPort());
        spPaymentOrderDetailBO.setExpectedLoadingDate(execute.getExpectedLoadingDate());
        spPaymentOrderDetailBO.setExpectedUnloadingDate(execute.getExpectedUnloadingWindow());
        spPaymentOrderDetailBO.setExpectedUnloadingPort(execute.getExpectedUnloadingPort());
        //实际卸载时间
        if(execute.getRealityLoadingDate()!=null){
            spPaymentOrderDetailBO.setRealityLoadingDate(execute.getRealityLoadingDate());
        }
        spPaymentOrderDetailBO.setPayableAmount(BigDecimal.valueOf(Long.parseLong(his.getFobCost())));
        SpArrangeSchemeDetail arrangeSchemeDetail = spArrangeSchemeDetailMapper.selectById(execute.getArrangeSchemeDetailId());
        if(arrangeSchemeDetail!=null){
            spPaymentOrderDetailBO.setEstimateLoadVolume(arrangeSchemeDetail.getLoadingCapacity());
        }
        spPaymentOrderDetailBO.setEstimateGoodsPrice(BigDecimal.valueOf(Long.parseLong(his.getFobCost())));
        spPaymentOrderService.synchronousPayOrderDetail(spPaymentOrderDetailBO);
        return order.getId();
    }

}
